import 'package:flutter/material.dart';
import 'package:flutter_riverpod/flutter_riverpod.dart';
import 'package:window_manager/window_manager.dart'; // 添加window_manager导入

import 'connectivity/connectivity_service.dart';
import 'sync/data_sync_service.dart';
import 'sync/offline_sync_service.dart'; // 添加离线同步服务
import '../presentation/providers/dependencies.dart';
import '../core/platform/platform_detector.dart'; // 添加平台检测导入

/// 应用初始化器
class AppInitializer extends ConsumerStatefulWidget {
  final Widget child;

  const AppInitializer({super.key, required this.child});

  @override
  ConsumerState<AppInitializer> createState() => _AppInitializerState();
}

class _AppInitializerState extends ConsumerState<AppInitializer> {
  bool _isInitialized = false;

  @override
  void initState() {
    super.initState();
    _initializeApp();
  }

  Future<void> _initializeApp() async {
    try {
      // 初始化窗口管理器（仅在桌面平台）
      if (!PlatformDetector.isWeb() && !PlatformDetector.isMobile()) {
        await windowManager.ensureInitialized();
      }

      // 从依赖注入中获取数据库实例，而不是创建新的实例
      final database = ref.read(databaseProvider);

      // 初始化网络连接服务
      final connectivityService = ConnectivityService();
      await connectivityService.initialize();

      // 使用依赖注入获取API服务
      final authApiService = ref.read(authApiServiceProvider);
      final projectApiService = ref.read(projectApiServiceProvider);
      final noteApiService = ref.read(noteApiServiceProvider); // 添加笔记API服务
      final todoApiService = ref.read(todoApiServiceProvider); // 添加待办API服务

      // 初始化离线同步服务
      final offlineSyncService = OfflineSyncService();
      await offlineSyncService.initialize(
        noteApiService: noteApiService,
        projectApiService: projectApiService,
        todoApiService: todoApiService, // 初始化待办API服务
        offlineDataManager: ref.read(offlineDataManagerProvider),
        offlineModeManager: ref.read(offlineModeManagerProvider),
      );

      // 初始化数据同步服务
      final dataSyncService = DataSyncService();
      await dataSyncService.initialize(
        database: database,
        projectApiService: projectApiService,
        authApiService: authApiService,
        noteApiService: noteApiService, // 初始化笔记API服务
        todoApiService: todoApiService, // 添加缺失的todoApiService参数
        connectivityService: connectivityService,
        offlineSyncService: offlineSyncService, // 初始化离线同步服务
      );

      // 初始化离线模式管理器
      final offlineModeManager = ref.read(offlineModeManagerProvider);
      await offlineModeManager.initialize(
        database: database,
        connectivityService: connectivityService,
        dataSyncService: dataSyncService,
      );

      // 不再在应用启动时自动检查认证状态
      // 用户需要手动登录
      setState(() {
        _isInitialized = true;
      });
    } catch (e) {
      // 处理初始化错误
      debugPrint('应用初始化失败: $e');
      // 即使初始化失败，我们也允许应用继续运行（离线模式）
      setState(() {
        _isInitialized = true;
      });
    }
  }

  @override
  Widget build(BuildContext context) {
    if (!_isInitialized) {
      return const MaterialApp(
        home: Scaffold(
          body: Center(
            child: CircularProgressIndicator(),
          ),
        ),
      );
    }

    return widget.child;
  }
}
